package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;

import com.pic4493.base.BaseUI;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.ESubscribe;
import com.pic4493.entities.EUser;
import com.pic4493.net.NetClientJ;
import com.pic4493.updater.TaskCheckVersion;
import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiImage;
import com.pic4493.utils.UtiStat;
import com.pic4493.utils.UtiUI;
import com.ppcodes.imageloader.core.DisplayImageOptions;
import com.ppcodes.imageloader.core.ImageLoader;
import com.ppcodes.imageloader.core.assist.FailReason;
import com.ppcodes.imageloader.core.assist.ImageLoadingListener;

public class UISplash extends BaseUI
{
   private DisplayImageOptions imgConfig = new DisplayImageOptions.Builder().cacheInMemory().cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();

   private ArrayList<ESubscribe> mList;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.uisplash);
	  Session.getInstance();
	  UtiUI.init(mContext);
	  UtiStat.init(this);
	  if (Session.getInstance().isAutoLogin())
	  {
		 Session.getInstance().loginAuto();
	  }
	  	  
	  executeAsyncTask("begin");
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {

   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("begin".equals(taskName))
	  {
		 return NetClientJ.GetHomeSubscribes();
	  }
	  else if ("pic".equals(taskName))
	  {
		 // 先把首页壁纸从本地读出加载在在缓存里面
		 Session.getInstance().picWallPaper = UtiImage.loadWallPaper(mContext);

		 // 再加载每日一图接口获取新壁纸地址
		 return NetClientJ.GetSplash2Photo();
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if (taskName.equals("begin"))
			   {
				  JSONObject object = data.getBody();
				  JSONArray subscibes = object.optJSONArray("subscibe");

				  ESubscribe sub = null;
				  mList = new ArrayList<ESubscribe>();
				  sub = new ESubscribe();
				  sub.setCanDelete(false);
				  sub.setCover(object.optString("wap_image"));
				  sub.setName("手机网站");
				  sub.setId("-1");
				  mList.add(sub);
				  sub = new ESubscribe();
				  sub.setCanDelete(false);
				  sub.setCover(object.optString("new_image"));
				  sub.setName("每日新图");
				  sub.setId("-2");
				  mList.add(sub);
				  if (subscibes != null)
				  {
					 for (int i = 0; i < subscibes.length(); i++)
					 {
						sub = new ESubscribe();
						sub.setCover(subscibes.getJSONObject(i).optString("ztcover"));
						sub.setId(subscibes.getJSONObject(i).optString("sid"));
						sub.setName(subscibes.getJSONObject(i).optString("ztname"));
						sub.setDescribe(subscibes.optJSONObject(i).optString("describe"));
						sub.setCanDelete(true);
						mList.add(sub);
					 }
				  }
				  if (Session.getInstance().isLogin())
				  {
					 sub = new ESubscribe();
					 sub.setCanDelete(false);
					 sub.setId("-3");
					 mList.add(sub);
				  }
				  executeAsyncTask("pic");// 继续读取图片
			   }
			   else if ("pic".equals(taskName))
			   {
				  final Intent intent = new Intent();
				  intent.putParcelableArrayListExtra(PubConst.Intent_Key.Subscribes, mList);
				  intent.setClass(UISplash.this, UISplash2.class);
				  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				  String url = data.getBody().optString("value");
				  // 开始读取每日一图的图片并一直等待,读取成功则更新缓存,失败则使用本地缓存
				  ImageLoader.getInstance().loadImage(mContext, url, imgConfig, new ImageLoadingListener()
				  {
					 @Override
					 public void onLoadingStarted()
					 {
					 }

					 @Override
					 public void onLoadingFailed(FailReason failReason)
					 {
						setResult(RESULT_OK);
						startActivity(intent);
						finish();
					 }

					 @Override
					 public void onLoadingComplete(Bitmap loadedImage)
					 {
						Session.getInstance().picCache = loadedImage;
						setResult(RESULT_OK);
						startActivity(intent);
						finish();
						overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
					 }

					 @Override
					 public void onLoadingCancelled()
					 {
						setResult(RESULT_OK);
						startActivity(intent);
						finish();
					 }
				  });
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowOKAlertDialogEX(UISplash.this, "提示", data.getHead().getRspMsg(), new OnClickListener()
			   {
				  @Override
				  public void onClick(DialogInterface dialog, int which)
				  {
					 finish();
					 System.exit(0);
				  }
			   });
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowOKAlertDialogEX(UISplash.this, "提示", "网络异常请稍候再试", new OnClickListener()
			{
			   @Override
			   public void onClick(DialogInterface dialog, int which)
			   {
				  finish();
				  System.exit(0);
			   }
			});
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UISplash_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
		 UtiDialog.getInstance().ShowOKAlertDialog(mContext, "提示", "网络异常,请稍候重试", new OnClickListener()
		 {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			   finish();
			   System.exit(0);
			}
		 });
	  }
   }
}
